import socket
import sys
from struct import pack, unpack

HOST = '127.0.0.1'               # Symbolic name meaning all available interfaces
PORT = 53              # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                              socket.SOCK_DGRAM, 0, socket.AI_PASSIVE):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except socket.error as msg:
        s = None
        continue
    try:
        s.bind(sa)
    except socket.error as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print 'could not open socket'
    sys.exit(1)
while 1:
    data, address = s.recvfrom(2048)
    try:
        sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sc.connect(('8.8.8.8', 53))
        datalen = len(data)
        print 'Data: ', repr(data)
        print 'Data length: ', datalen
        print 'Connnect by', address
        sc.send(pack('H',socket.htons(datalen)) + data)
        rdata_raw = sc.recv(2048)
        rdata_rawlen = len(rdata_raw)
        print 'H'+str(rdata_rawlen-2)+'p'
        (rdatalen, rdata) = unpack('H'+str(rdata_rawlen-2)+'p',rdata_raw)
        rdata = rdata_raw[2:]
        rdatalen = socket.htons(rdatalen)
        print 'Response:',repr(rdata)
        print 'Response length: ',rdatalen
        s.sendto(rdata,address)
        sc.close()
    except socket.error as msg:
        print msg
        sc.close()
        continue
    
 
    